package com.juyu.miliao.authentication.service;

import com.juyu.miliao.authentication.service.cache.ConfigQqCacheService;
import com.juyu.miliao.common.domain.ConfigQq;
import com.juyu.miliao.common.domain.dto.QqDTO;
import com.juyu.miliao.common.exception.ConsumeRuntimeException;
import com.juyu.miliao.common.util.CommonUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import static com.juyu.miliao.common.msg.CommonErrorMsgs.SERVER_ERROR;

/**
 * @Auther: 卜加超
 * @Date: 2019/6/4 15:16
 * @Description:
 */
@Service
@Slf4j
public class ConfigQqService {
    @Resource
    private ConfigQqCacheService configQqCacheService;

    public Map<String, QqDTO> getConfigQq(){
        List<ConfigQq> list = configQqCacheService.getQqDTOList();
        if (list.isEmpty()) {
            throw new ConsumeRuntimeException(SERVER_ERROR);
        }
        Map<String, QqDTO> map = new HashMap<>((int) Math.ceil(list.size() / 0.75));
        String key;
        QqDTO dto;
        for (ConfigQq configQq : list) {
            log.info("缓存cache中list中的值:"+configQq);
            key = configQq.getAppPackageId().trim() + "_" + CommonUtil.null2String(configQq.getPhoneSystem());
            dto = new QqDTO();
            dto.setAppid(configQq.getAppid().trim());
            map.put(key, dto);
        }
        return map;
    }

    public QqDTO getConfig(String appPackageId, int phoneSystem) {
        Map<String, QqDTO> map = getConfigQq();
        String key = appPackageId + "_" + CommonUtil.null2String(phoneSystem);
        QqDTO qqDTO = map.get(key);
        if (qqDTO == null) {
            log.error("获取qq配置为空,请检查数据库config_qq配置,key={}", key);
            throw new ConsumeRuntimeException(SERVER_ERROR);
        }
        return qqDTO;
    }
}
